<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="vjImUBDCK8Rg9G13vkIip_GUsZTtVV6s-XdSk81-jzA" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kotlin," />





  <link rel="alternate" href="/atom.xml" title="旺仔的个人博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.png?v=5.1.2" />






<meta name="description" content="本文是关于Kotlin的属性和字段相关，涉及到有变量、常量还有延迟加载属性。">
<meta name="keywords" content="Kotlin">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin学习_属性和字段">
<meta property="og:url" content="http://www.jowanxu.top/2017/02/28/Kotlin学习_属性和字段/index.html">
<meta property="og:site_name" content="旺仔的个人博客">
<meta property="og:description" content="本文是关于Kotlin的属性和字段相关，涉及到有变量、常量还有延迟加载属性。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-ccded53b8ff4af4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-50b4f791af0d4b1c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-fe63443369944a26.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-29T00:20:30.234Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kotlin学习_属性和字段">
<meta name="twitter:description" content="本文是关于Kotlin的属性和字段相关，涉及到有变量、常量还有延迟加载属性。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1241355-ccded53b8ff4af4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.jowanxu.top/2017/02/28/Kotlin学习_属性和字段/"/>





  <title>Kotlin学习_属性和字段 | 旺仔的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/wangzailfm"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">旺仔的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">叫我旺仔<br/>Android Developer</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.jowanxu.top/2017/02/28/Kotlin学习_属性和字段/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jowan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="旺仔的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kotlin学习_属性和字段</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-28T21:46:59+08:00">
                2017-02-28
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-11-29T08:20:30+08:00">
                2017-11-29
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 文章热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <br/>
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">文章字数</span>
                
                <span title="文章字数">
                  1,242 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长需</span>
                
                <span title="阅读时长需">
                  5 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://upload-images.jianshu.io/upload_images/1241355-ccded53b8ff4af4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Kotlin"></p>
<p>本文是关于Kotlin的属性和字段相关，涉及到有变量、常量还有延迟加载属性。<br><a id="more"></a></p>
<h2 id="声明属性-Declaring-Properties"><a href="#声明属性-Declaring-Properties" class="headerlink" title="声明属性(Declaring Properties)"></a>声明属性(Declaring Properties)</h2><p>Kotlin中可以使用<code>var</code>关键字声明可变属性，或者用<code>val</code>关键字声明只读属性，属性的类型在后面，变量名在签名，中间加冒号和空格。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Address</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">var</span> name: String = ...</div><div class="line">    <span class="keyword">public</span> <span class="keyword">var</span> street: String = ...</div><div class="line">    <span class="keyword">public</span> <span class="keyword">var</span> city: String = ...</div><div class="line">    <span class="keyword">public</span> <span class="keyword">var</span> state: String? = ...</div><div class="line">    <span class="keyword">public</span> <span class="keyword">var</span> zip: String = ...</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>调用的时候与Java一样，通过变量名直接使用一个属性<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">copyAddress</span><span class="params">(address: <span class="type">Address</span>)</span></span>: Address &#123;</div><div class="line">    <span class="keyword">val</span> result = Address() <span class="comment">// Kotlin不需要使用new关键字</span></div><div class="line">    result.name = address.name</div><div class="line">    result.street = address.street</div><div class="line">    <span class="comment">// ...</span></div><div class="line">    <span class="keyword">return</span> result</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="Getter和Setter-Getters-and-Setters"><a href="#Getter和Setter-Getters-and-Setters" class="headerlink" title="Getter和Setter(Getters and Setters)"></a>Getter和Setter(Getters and Setters)</h2><p>声明属性的完整语法如下，语法中的初始化语句，<code>getter</code>和<code>setter</code>都是可选的<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> &lt;propertyName&gt;: &lt;PropertyType&gt; [= &lt;property_initializer&gt;]</div><div class="line">    [&lt;getter&gt;]</div><div class="line">    [&lt;setter&gt;]</div></pre></td></tr></table></figure></p>
<p>如果属性类型可以从初始化语句或者类的成员函数中推断出来，那就可以省去类型，<code>val</code>不允许设置<code>setter</code>函数，以为它是只读的。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> allByDefault: <span class="built_in">Int</span>? <span class="comment">// 错误: 需要一个初始化语句, 默认实现了 getter 和 setter 方法</span></div><div class="line"><span class="keyword">var</span> initialized = <span class="number">1</span> <span class="comment">// 类型为 Int, 默认实现了 getter 和 setter</span></div><div class="line"><span class="keyword">val</span> simple: <span class="built_in">Int</span>? <span class="comment">// 类型为 Int ，默认实现 getter ，但必须在构造函数中初始化</span></div><div class="line"><span class="keyword">val</span> inferredType = <span class="number">1</span> <span class="comment">// 类型为 Int 类型,默认实现 getter</span></div></pre></td></tr></table></figure></p>
<p>可以自定义访问器(<code>getter</code>)和自定义<code>setter</code>，<code>setter</code>的参数名默认是<code>value</code>，也可以自定义<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> isEmpty: <span class="built_in">Boolean</span></div><div class="line">    <span class="keyword">get</span>() = <span class="keyword">this</span>.size == <span class="number">0</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> stringRepresentation: String</div><div class="line">    <span class="keyword">get</span>() = <span class="keyword">this</span>.toString()</div><div class="line">    <span class="keyword">set</span> (value) &#123;</div><div class="line">        setDataFormString(value) <span class="comment">// 格式化字符串,并且将值重新赋值给其他元素</span></div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>如果需要设置访问器的可见性或者设置注解，又不改变原来的实现，则可以设置一个不带函数的访问器<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> setterVisibility: String = <span class="string">"abc"</span> <span class="comment">// 非空类型必须初始化</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">set</span> <span class="comment">// setter是私有的并且有默认的实现</span></div><div class="line"></div><div class="line"><span class="keyword">var</span> setterWithAnnotation: Any? = <span class="literal">null</span> <span class="comment">// 设置为可空</span></div><div class="line">    <span class="meta">@Inject</span> <span class="keyword">set</span> <span class="comment">// 用 Inject 注解 setter</span></div></pre></td></tr></table></figure></p>
<h3 id="备用字段-Backing-Fields"><a href="#备用字段-Backing-Fields" class="headerlink" title="备用字段(Backing Fields)"></a>备用字段(Backing Fields)</h3><p>Kotlin中的类并不允许使用字段，在自定义<code>getter</code>和<code>setter</code>的时候，可以使用<code>field</code>来起到局部变量的作用。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> counter = <span class="number">0</span> <span class="comment">//初始化值会直接写入备用字段</span></div><div class="line">    <span class="keyword">get</span>() = field</div><div class="line">    <span class="keyword">set</span>(value) &#123;</div><div class="line">        <span class="keyword">if</span> (value &gt;= <span class="number">0</span>)</div><div class="line">            field  = value</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>编译器会检查访问器的代码,如果使用了备用字段(或者访问器是默认的实现逻辑)，就会自动生成备用字段，否则就不会。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 这种情况并不需要备用字段，所有不会生成备用字段</span></div><div class="line"><span class="keyword">val</span> isEmpty: <span class="built_in">Boolean</span></div><div class="line">    <span class="keyword">get</span>() = <span class="keyword">this</span>.size == <span class="number">0</span></div></pre></td></tr></table></figure></p>
<blockquote>
<p>注意：<code>field</code>标识符只允许在属性的访问器函数内使用. </p>
</blockquote>
<h3 id="备用属性-Backing-Properties"><a href="#备用属性-Backing-Properties" class="headerlink" title="备用属性(Backing Properties)"></a>备用属性(Backing Properties)</h3><p>备用属性，可以看作是备用变量(Backing Fields)的变种，其实际上也是隐含试的对属性值的初始化声明，避免了空指针。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> <span class="keyword">var</span> _table: Map&lt;String, <span class="built_in">Int</span>&gt;? = <span class="literal">null</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">val</span> table: Map&lt;String, <span class="built_in">Int</span>&gt;</div><div class="line">    <span class="keyword">get</span>() &#123;</div><div class="line">        <span class="keyword">if</span> (_table == <span class="literal">null</span>) &#123;</div><div class="line">            _table = HashMap() <span class="comment">// 参数类型是自动推导</span></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> _table ?: <span class="keyword">throw</span> AssertionError(<span class="string">"Set to null by another thread"</span>)</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>不管是备用变量或者备用属性，都是Kotlin对于空指针的一种解决方案，可以避免函数访问私有属性而破坏它的结构。</p>
<h2 id="编译时常量-Compile-Time-Constants"><a href="#编译时常量-Compile-Time-Constants" class="headerlink" title="编译时常量(Compile-Time Constants)"></a>编译时常量(Compile-Time Constants)</h2><p>那些在编译时就能知道具体值的属性可以使用<code>const</code>修饰符标记为编译时常量. 这种属性需要同时满足以下条件:</p>
<ul>
<li>顶层或对象的成员(Top-level or member of an object)</li>
<li>以String或基本类型进行初始化</li>
<li>没有自定义getter</li>
</ul>
<p>这种属性可以当作注解使用<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">const <span class="keyword">val</span> SUBSYSTEM_DEPRECATED: String = <span class="string">"This subsystem is deprecated"</span></div><div class="line"><span class="meta">@Deprected(SUBSYSTEM_DEPRECATED)</span> <span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">()</span></span> &#123; ... &#125;</div></pre></td></tr></table></figure></p>
<h2 id="Top-level-顶级"><a href="#Top-level-顶级" class="headerlink" title="Top-level(顶级)"></a>Top-level(顶级)</h2><p><code>Top-level</code>属性或者方法，与<code>class</code>同级，如下面所示，类名是<code>Kot</code><br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> foo.bar</div><div class="line"></div><div class="line"><span class="keyword">val</span> prop: String = <span class="string">"top-level-prop"</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">demo</span><span class="params">()</span></span> &#123;</div><div class="line">    loge(<span class="string">"top-level"</span>, <span class="string">"top-level-demo()"</span>)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Kot</span> </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">v</span><span class="params">()</span></span> &#123;</div><div class="line">        loge(<span class="string">"top-level"</span>, prop)</div><div class="line">        demo()</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在编译成class的时候，会把<code>Top-level</code>的属性和函数创建到以类名+<code>Kt</code>为名的<code>class</code>文件中</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-50b4f791af0d4b1c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="KotKt.class"></p>
<p><code>Top-level</code>调用的时候类似于调用扩展函数那样，直接调用属性或者函数。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">loge(<span class="string">"top-level"</span>, prop)</div><div class="line">demo()</div></pre></td></tr></table></figure></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-fe63443369944a26.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="log"></p>
<h2 id="延迟初始化属性-Late-Initialized-Properties"><a href="#延迟初始化属性-Late-Initialized-Properties" class="headerlink" title="延迟初始化属性(Late-Initialized Properties)"></a>延迟初始化属性(Late-Initialized Properties)</h2><p>在Kotlin中，声明为具有非空类型的属性必须在构造函数中初始化，但是往往不希望在构造函数中初始化，例如在通过依赖注入或单元测试的设置方法来初始化属性的时候，不能在构造器中提供一个非空的初始化语句，为了处理这种情况，就要在属性上加<code>lateinit</code>关键字来延迟初始化<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTest</span> </span>&#123;</div><div class="line">    <span class="keyword">lateinit</span> <span class="keyword">var</span> subject: TestSubject</div><div class="line"></div><div class="line">    <span class="meta">@SetUp</span> <span class="function"><span class="keyword">fun</span> <span class="title">setup</span><span class="params">()</span></span> &#123;</div><div class="line">        subject = TestSubject()</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Test</span> <span class="function"><span class="keyword">fun</span> <span class="title">test</span><span class="params">()</span></span> &#123;</div><div class="line">        subject.method() </div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><code>lateinit</code>只能够在<code>var</code>类型的属性中，不能用于构造函数，而且属性不能有自定义的<code>getter</code>和<code>setting</code>，这些属性必须是非空类型，并且不能是基本类型。</p>
<blockquote>
<p>如果在一个延迟初始化的属性初始化前调用,会导致一个特定异常,调用的时候值还没有初始化.</p>
</blockquote>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jowan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.jowanxu.top/2017/02/28/Kotlin学习_属性和字段/" title="Kotlin学习_属性和字段">http://www.jowanxu.top/2017/02/28/Kotlin学习_属性和字段/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kotlin/" rel="tag"><i class="fa fa-tag"></i> Kotlin</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/26/Kotlin学习_基本语法/" rel="next" title="Kotlin学习_基本语法">
                <i class="fa fa-chevron-left"></i> Kotlin学习_基本语法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/01/Kotlin学习_基本类型/" rel="prev" title="Kotlin学习_基本类型（Basic Types）">
                Kotlin学习_基本类型（Basic Types） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjA1My84NjE3"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Jowan" />
          <p class="site-author-name" itemprop="name">Jowan</p>
           
              <p class="site-description motion-element" itemprop="description">叫我旺仔<br/>Android Developer</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/111824269044709365866" target="_blank" title="Google">
                  
                    
                      Google
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/wangzailfm" target="_blank" title="GitHub">
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/809077554" target="_blank" title="微博">
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="673173629@qq.com" target="_blank" title="E-Mail">
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/u011976726" target="_blank" title="CSDN">
                  
                    
                      CSDN
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5509a21c1623" target="_blank" title="简书">
                  
                    
                      简书
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wanandroid.com/" title="WanAndroid" target="_blank">WanAndroid</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#声明属性-Declaring-Properties"><span class="nav-number">1.</span> <span class="nav-text">声明属性(Declaring Properties)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Getter和Setter-Getters-and-Setters"><span class="nav-number">2.</span> <span class="nav-text">Getter和Setter(Getters and Setters)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#备用字段-Backing-Fields"><span class="nav-number">2.1.</span> <span class="nav-text">备用字段(Backing Fields)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#备用属性-Backing-Properties"><span class="nav-number">2.2.</span> <span class="nav-text">备用属性(Backing Properties)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编译时常量-Compile-Time-Constants"><span class="nav-number">3.</span> <span class="nav-text">编译时常量(Compile-Time Constants)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Top-level-顶级"><span class="nav-number">4.</span> <span class="nav-text">Top-level(顶级)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#延迟初始化属性-Late-Initialized-Properties"><span class="nav-number">5.</span> <span class="nav-text">延迟初始化属性(Late-Initialized Properties)</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jowan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
